package com.share.ai.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class FileUtil {
    Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static List<String> readByLineFromCp(String filename) {
        InputStream in = FileUtil.class.getClassLoader().getResourceAsStream(filename);
        return readByLine(in);
    }

    public static List<String> readByLine(String filePath) {
        return readByLine(new File(filePath));
    }

    public static List<String> readByLine(InputStream is) {
        List<String> list = new LinkedList<>();

        String line = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                list.add(line);
            }

        } catch (Exception e) {
            log.error("文件读取异常", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }

    public static List<String> readByLine(File file) {
        List<String> list = new LinkedList<>();
        if (file == null || !file.exists()) {
            return list;
        }

        String line = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                list.add(line);
            }

        } catch (Exception e) {
            log.error("文件读取异常", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }

    public static String read(String filePath) {
        return read(new File(filePath));
    }

    public static String read(File filePath) {
        byte[] bytes = readByte(filePath);
        return new String(bytes);
    }

    public static byte[] readByte(String filePath) {
        if (StrUtil.isBlank(filePath)) {
            return null;
        }
        return readByte(new File(filePath));
    }

    /**
     * 读取文件
     *
     * @param file
     * @return
     */
    public static byte[] readByte(File file) {
        if (file == null && !file.exists()) {
            return null;
        }

        try {
            InputStream is = new FileInputStream(file);

            //读取数据
            return readByte(is);
        } catch (Exception e) {
            log.error("文件读取异常filePath={}", file.getAbsoluteFile(), e);
        }
        return null;
    }

    public static byte[] readByte(InputStream is) {
        ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
        try {
            int len;
            byte[] temp = new byte[4096];
            while ((len = is.read(temp)) != -1) {
                outBuffer.write(temp, 0, len);
            }
        } catch (Exception e) {
            log.error("流读取异常", e);
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("流关闭异常", e);
                    return null;
                }
            }
        }
        return outBuffer.toByteArray();
    }


    public static String readFromCp(String filename) throws Exception {
        InputStream in = FileUtil.class.getClassLoader().getResourceAsStream(filename);
        byte[] bytes = readByte(in);
        return new String(bytes);
    }

    public static Properties readPropertiesFromHome(String filename) throws Exception {
        String home = System.getProperty("user.home");
        String filePath = home + File.separator + filename;
        return readProperties(filePath);
    }

    public static boolean write(String filePath, String fileContent, boolean isOver) {
        File file = new File(filePath);
        if (file.exists() && isOver) {
            file.delete();
        }
        return write(file, fileContent);
    }

    public static boolean write(String filePath, String fileContent) {
        File file = new File(filePath);
        return write(file, fileContent);
    }

    public static boolean write(File file, String fileContent) {
        byte[] bytes = null;
        if (StrUtil.isNotBlank(fileContent)) {
            //使用utf-8写入文件,gbk跨系统容易出问题
            bytes = fileContent.getBytes(StandardCharsets.UTF_8);
        }
        return writeByte(file, bytes);
    }

    public static boolean write(File file, byte[] bytes) {
        return writeByte(file, bytes);
    }

    public static boolean writeByte(String filePath, byte[] bytes) {
        if (StrUtil.isBlank(filePath)) {
            return false;
        }

        File file = new File(filePath);
        return writeByte(file, bytes);
    }

    /**
     * 将数据写入文件
     *
     * @param file  文件路径
     * @param bytes 文件内容(如果内容空,则只创建文件)
     * @return
     */
    public static boolean writeByte(File file, byte[] bytes) {
        if (file == null) {
            return false;
        }

        //文件中无内容
        if (bytes == null) {
            bytes = new byte[0];
        }

        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(bytes);
            return true;
        } catch (Exception e) {
            log.error("文件写异常filePath={}", file.getAbsoluteFile(), e);
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("输出流关闭异常filePath={}", file.getAbsoluteFile(), e);
                }
            }
        }
    }


    public static Properties readProperties(File file) {
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            properties.load(bufferedReader);
        } catch (Exception e) {
            log.error("Properties文件读取失败", e);
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return properties;
    }

    public static Properties readProperties(String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            return readProperties(f);
        } else {
            return null;
        }
    }

    public static List<File> listCurrentDirFile(File file, String include, String endWith) {
        List<File> list = new LinkedList<>();
        if (file != null) {
            if (!file.exists()) {
                return list;
            }

            if (file.isFile()) {
                return list;
            }

            int paramNotNullNum = 0;
            if (include != null && include.trim().length() > 0) {
                paramNotNullNum++;
            }
            if (endWith != null && endWith.trim().length() > 0) {
                paramNotNullNum++;
            }

            File[] files = file.listFiles();
            for (File f : files) {
                if (f.isDirectory()) {
                    continue;
                }

                int condition = 0;
                String path = f.getAbsolutePath();
                if (include != null && path.contains(include)) {
                    condition++;
                }

                if (endWith != null && path.endsWith(endWith)) {
                    condition++;
                }

                if (condition == paramNotNullNum) {
                    list.add(f);
                }
            }
        }
        return list;
    }

    public static List<File> listCurrentDirFile(String dirPath, String include, String endWith) {
        if (StrUtil.isBlank(dirPath)) {
            return new LinkedList<>();
        }
        return listCurrentDirFile(new File(dirPath), include, endWith);
    }

    public static List<File> listCurrentDirFile(File file) {
        return listCurrentDirFile(file, null, null);
    }

    public static List<File> listCurrentDirFile(String dirPath) {
        return listCurrentDirFile(dirPath, null, null);
    }

    public static List<File> listFile(File file) {
        return listFile(file, null, null);
    }

    public static List<File> listFile(String dirPath) {
        if (StrUtil.isBlank(dirPath)) {
            return new LinkedList<>();
        }
        return listFile(new File(dirPath), null, null);
    }

    public static List<File> listFile(String dirPath, String inclouds, String endWith) {
        return listFile(dirPath, inclouds, endWith, null);
    }

    public static List<File> listFile(String dirPath, String inclouds, String endWith, Integer limit) {
        if (StrUtil.isBlank(dirPath)) {
            return new LinkedList<>();
        }
        return listFile(new File(dirPath), inclouds, endWith, limit);
    }

    public static List<File> listFile(File file, String includes, String endWith) {
        return listFile(file, includes, endWith, null);
    }

    public static List<File> listFile(File file, String includes, String endWith, Integer limit) {
        //公共参数
        List<String> includeList = new LinkedList<>();
        if (includes != null && includes.trim().length() > 0) {
            String[] split = includes.split(",");
            int len = split.length;
            for (int i = 0; i < len; i++) {
                if (split[i] != null || split[i].trim().length() > 0) {
                    includeList.add(split[i].trim());
                }
            }
        }

        return listFile(file, includeList, endWith, limit);
    }

    /***
     * 获取指定目录下的所有的文件（不包括文件夹），采用了递归
     *
     * @param file
     * @param includeList 支持多个参数
     * @return
     */
    public static List<File> listFile(File file, List<String> includeList, String endWith, Integer limit) {
        List<File> fileList = new LinkedList<>();
        if (file == null) {
            return fileList;
        }

        if (!file.exists()) {
            return fileList;
        }

        if (file.isFile()) {
            return fileList;
        }

        int paramNotNullNum = 0;
        if (includeList.size() > 0) {
            paramNotNullNum++;
        }

        if (endWith != null && endWith.trim().length() > 0) {
            paramNotNullNum += 64;
        }

        File[] childFileList = file.listFiles();
        for (File childFile : childFileList) {
            if (limit != null && fileList.size() >= limit) {
                //超过了就退出
                break;
            }

            if (childFile.isFile()) {
                int condition = 0;
                String path = childFile.getAbsolutePath();
                if (includeList.size() > 0) {
                    int tmpCount = 0;
                    for (String incloud : includeList) {
                        if (path.contains(incloud)) {
                            tmpCount++;
                        } else {
                            //不命中直接跳出
                            break;
                        }
                    }
                    if (tmpCount == includeList.size()) {
                        condition++;
                    }
                }

                if (endWith != null && path.endsWith(endWith)) {
                    condition += 64;
                }

                if (condition == paramNotNullNum) {
                    if (limit != null && fileList.size() >= limit) {
                        //超过了就退出
                        break;
                    }
                    fileList.add(childFile);
                }
            } else {
                fileList.addAll(listFile(childFile, includeList, endWith, limit));
            }
        }

        return fileList;
    }

    public static int copyFile(File srcFile, File desFile) {
        return copyFile(srcFile, desFile, true);
    }

    public static int copyFile(File srcFile, File desFile, boolean isOver) {
        if (!srcFile.exists()) {
            return -2;
        }

        Boolean writeFlag = true;
        if (desFile.exists()) {
            if (isOver) {
                desFile.delete();
            } else {
                writeFlag = false;
            }
        }

        if (writeFlag) {
            try {
                byte[] bytes = FileUtil.readByte(srcFile);
                FileUtil.writeByte(desFile, bytes);
            } catch (Exception e) {
                log.error("文件读取异常", e);
                return -1;
            }
        }
        return 1;
    }

    public static boolean mkdir(File webFilePath) {
        if (!webFilePath.exists()) {
            File parentFile = webFilePath.getParentFile();
            parentFile.mkdirs();
            return true;
        } else {
            return true;
        }
    }

    /**
     * 模拟tail -f  方式读取文件 --- 待验证
     *
     * @param logFile
     * @param positionOffset
     * @param tailNumOfLines
     * @return
     * @throws IOException
     */
    public Map<String, Object> tailLogFile(File logFile, long positionOffset, int tailNumOfLines) throws IOException {
        LinkedList<String> list = new LinkedList<>();
        Map<String, Object> result = new HashMap<>();

        try (RandomAccessFile raf = new RandomAccessFile(logFile, "r")) {
            long lenOfFile = raf.length();
            long realOffset = Math.max(positionOffset, lenOfFile - 1000000);    //最多加载1MB的日志数据
            result.put("startPosition", realOffset);
            result.put("endPosition", lenOfFile);
            raf.seek(realOffset);
            while (raf.getFilePointer() < lenOfFile) {
                String line = null;

                try {
                    line = raf.readLine();
                } catch (IOException var4) {
                    //读取出错了也要继续
                    throw new RuntimeException(var4);
                }
                if (StrUtil.isNotEmpty(line)) {
                    list.add(line);
                }
            }

            result.put("linesOfLog", list.subList(Math.max(0, list.size() - tailNumOfLines), list.size()));
            return result;
        }
    }
}
